<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/5/12
 * Time: 11:29
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\controller\v1;

use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\NewsLists;
use app\common\model\NewsSee;
use think\App;

class News extends Base
{
    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new NewsLists();
    }

    /**
     * @return array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNewsListInfo()
    {
        $limit = $this->request->param('limit', 10, 'intval');
        $page = $this->request->param('page', 1, 'intval');

        try {
            $row = $this->model->getPaginateByNormalListInfo([], $limit, "id,title,logo,images,create_time,type,sort,see_type,thumb_title", 'sort desc,id desc');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "查询异常");
        }
        $lists = [];
        foreach ($row['data'] as $k => $v) {
            $lists[$k] = $v;
            $lists[$k]['time'] = strtotime($v['create_time']);
            $lists[$k]['images'] = explode('|', $v['images']);
            //查询查看次数
            $obj_news_see = new NewsSee();
            if ($v['see_type'] == 1) {
                $see = $obj_news_see->getUserByCount($v['id']);
            }else{
                $see = $obj_news_see->getSeeByCount($v['id']);
            }
            $lists[$k]['clickNum'] = $see['count'] ?? 0;

        }
        return Show::json_show(Status::mini_normal, "ok", $lists, $row['total'], false, $row['last_page']);
    }

    /**
     * @return array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNewsByDetail()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 0) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        try {
            $row = $this->model->getBaseById($id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        $row['description'] = htmlspecialchars_decode($row['description']);
        if ($row['see_type'] == 1) {
            //记录用户次数
            (new NewsSee())->setNewsSeeByUser($this->m_openid, $row['id']);
        } else {
            //记录浏览次数
            (new NewsSee())->save([
                "openid" => $this->m_openid,
                "news_id" => $row['id']
            ]);
        }
        //记录次数
        return Show::json_show(Status::mini_normal, "ok", $row);
    }
}